package com.pompom.workers;

import java.util.HashMap;
import java.util.Map;

import com.pompom.matchcrawler.JobManager;

public abstract class AbstractWorker implements Runnable{

Map<String, String> parameters = new HashMap<String, String>();
public int sleepTimeSec, sleepTimeMinutes;
public String jobClass="";
public long lastExecution;
private boolean stopWork=false;
public int sleepPlus =0;
protected JobManager jobManager;
public void putParameter(String paramName, String paramValue)
{
	parameters.put(paramName, paramValue);
}

public String getParameter(String paramName)
{
	return parameters.get(paramName);
}
public abstract void work();
public abstract void setParameters();



public boolean checkPeriod()
{
	if (System.currentTimeMillis() - lastExecution > (sleepTimeSec+sleepTimeMinutes*60 )*1000 )
			{
			lastExecution = System.currentTimeMillis();
			return true;
			}
	return false;
}

public boolean isStopWork() {
	return stopWork;
}

public void setStopWork(boolean stopWork) {
	this.stopWork = stopWork;
}
	

@Override
public void run() {
  
	System.out.println("Starting "+jobClass);
	while(!stopWork)
	{
		
		 try{
			if (this.checkPeriod())
				this.work();
		 }
		 catch (Exception e)
		 {
			 e.printStackTrace();
			 System.out.println("Job "+this+" terminated with fault");
			 this.setStopWork(true);
		 }
		 
		try {
			Thread.sleep(90+sleepPlus);
		} catch (InterruptedException e) { 
			e.printStackTrace();
		}
	}
	
	System.out.println("Ending "+jobClass);
	
}

public JobManager getJobManager() {
	return jobManager;
}

public void setJobManager(JobManager jobManager) {
	this.jobManager = jobManager;
}



}
